<?php
declare (strict_types = 1);

namespace app\api\controller\ucenter;

use app\common\system\logic\UserRoleLogic;
use fast\Redis;
use Firebase\JWT\JWT;
use think\captcha\facade\Captcha;
use think\Request;

class Passport
{
    protected $request;

    public function __construct(Request $request)
    {
        $this->request = $request;
    }

    public function login()
    {
        $post = $this->request->post();

        // 前端验证
        $loginValidate = new \app\common\system\validate\LoginValidate();
        if (!$loginValidate->check($post)) {
            return error([], $loginValidate->getError());
        }

        $redis = Redis::init();
        $cacheName = 'verify_' . $post['uuid'];
        $key = $redis->get($cacheName);
        if (empty($key)) return error([], '验证码已过期');

        // 检测验证码
        $vlidate = password_verify(mb_strtolower($post['verify'], 'UTF-8'), $key);
        if (!$vlidate) {
            $redis->del($cacheName);
            return error([], '验证码错误');
        }

        // 获取登录配置
        $systemConfigLogic = new \app\common\config\logic\ConfigSystem();
        $loginConfig = $systemConfigLogic->getConfigItem('login');

        $passportLogic = new \app\common\system\logic\PassportLogic();
        // 登录次数检测
        if ($loginConfig['incorrect_times'] > 0) {
            $loginTimes = $passportLogic->getLoginTimes($post['username']);
            $passportLogic->resetLoginTimes($post['username']);
            if ($loginTimes > $loginConfig['incorrect_times']) return error([], '登录次数过多');
        }

        ### 密码检测
        $where = [];
        $where[] = ['nickname', '=', $post['username']];
        $where[] = ['password', '=', md5($post['password'])];
        $model = new \app\common\system\model\User();
        $user = $model->where($where)->find();
        if(!$user) {
            // 记录登录次数
            if ($loginConfig['incorrect_times'] > 0) $passportLogic->incrLoginTimes($post['username']);
            return error([], '账号或者密码错误');
        } else {
            unset($user['password']);
            // 重置登录次数
            if ($loginConfig['incorrect_times'] > 0) $passportLogic->resetLoginTimes($post['username']);
        }

        $ini = config();
        $key = $ini['app']['jwt'];
        $data = $user->getData();

        if ($this->request->isMobile()){
            $data['client'] = 'mobile';
        } else {
            $data['client'] = 'pc';
        }

        $token = JWT::encode($data, $key, 'HS256');

        // 记录登陆日志
        \app\common\system\model\LoginRecord::write($user['id'], $this->request->ip());

        // 返回登录结果
        $result['token'] = $token;
        $result['user'] = $user;

        // 获取用户的功能节点
        $userRoleLogic = new UserRoleLogic();
        $roles = $userRoleLogic->getUserRole($user['id'], false);
        $result['roles'] = array_column($roles, 'title');

        return success($result, '登录成功');
    }

    // 图片验证码, 关联到前后端分离的
    public function captcha()
    {
        $uniqid = uniqid();
        $rs = Captcha::create();
        $base64 = "data:image/png;base64," . base64_encode($rs->getData());
        $key = session('captcha.key');
        
        $redis = Redis::init();
        $redis->set('verify_' .$uniqid, $key, 300);
        
        return success(['uuid' => $uniqid, 'captcha' => $base64]);
    }

    // 短信验证码
    public function code()
    {

    }

    public function system()
    {
        $model = new \app\common\config\model\ConfigSystem();
        $result = [];
        $result['website'] = $model->where('title', 'website')->find();

        return success($result);
    }

    public function wechat()
    {
        $model = new \app\common\config\model\ConfigSystem();
        $row = $model->where('title', 'work_wechat')->find();
        $result = $row['content'];
        unset($result['secret']);

        return success($result);
    }

    public function wechatLogin()
    {
        
    }
}
